<?php

namespace app\api\controller;

use think\Controller;
use think\facade\App;

class Area extends Basic
{
    public function getCityList()
    {
        $get = input('get.');

        $data = $where = [];
        $where = ['level' => 2];
        $data['where'] = $where;
        $data['order'] = 'first asc';
        $data['nolimit'] = 1;
        $list = $this->listTable('area', $data);

        $list = $this->groupByInitials($list);
        $data['list'] = $list;
        return $this->json($data, 1000);
    }

    public function groupByInitials($contact)
    {
        $data = [];
        //给所有数组进行A-Z分类
        foreach ($contact as $val) {
            if (empty($data[$val['first']])) {
                $data[$val['first']] = [];
            }
            $data[$val['first']][] = $val;
        }
        //按照键名排序
        ksort($data);
        foreach ($data as $k => $vv) {
            foreach ($contact as $item) {
                if($k == $val['first']) {
                    $data[$k][] = $item;
                }
            }
        }

        return $data;
    }

    //跟进地区id 获取相应的数据
    public function getArea($list)
    {
        $area = $this->getCacheWithLevel(false, 2);
        $data = [];
        if ($list) {
            foreach ($list as $k => $v) {
                if (isset($area[$v])) {
                    $data[$v] = $area[$v];
                }
            }
        } else {
            $data = $area;
        }
        return $data;
    }

    /**
     * 获取多级地区
     */
    public function areaTree()
    {
        $level = input('level', false);
        $type = input('type', 0);
        if (!$level) {
            $areaTree = cache("areaTree" . '_' . $type);
            if (!$areaTree) {
                $area = $this->getCache();
                $tree = [];
                foreach ($area as $k => $v) {
                    $temp = [];
                    $v = object_array($v);
                    if ($type) {
                        $temp['title'] = $v['name'];
                        $temp['key'] = $v['id'];
                        $temp['pid'] = $v['pid'];
                    } else {
                        $temp['value'] = $v['id'];
                        $temp['label'] = $v['name'];
                        $temp['pid'] = $v['pid'];
                    }

                    $tree[] = $temp;
                }

                $arr = $this->resetArea($tree, [0], $type);
                cache("areaTree", $arr, '', 'area');
                $areaTree = $arr;
            }
        } else {
            $areaTree = '';
            if (!$areaTree) {
                $area = $this->getCacheWithLevel(false, $level);
                $tree = [];
                foreach ($area as $k => $v) {
                    $temp = [];
                    $v = object_array($v);
                    if ($type) {
                        $temp['title'] = $v['name'];
                        $temp['key'] = $v['id'];
                        $temp['pid'] = $v['pid'];
                    } else {
                        $temp['value'] = $v['id'];
                        $temp['label'] = $v['name'];
                        $temp['pid'] = $v['pid'];
                    }
                    $tree[] = $temp;
                }
                $arr = self::resetArea($tree, [0], $type);
                cache("areaTree_" . $level . '_' . $type, $arr, null, 'area');
                $areaTree = $arr;
            }
        }
        return $this->json($areaTree, 1000);
    }
    private function resetArea($data, $pids = [0], $type)
    {
        $d = []; //需要返回的数组
        $p = []; //省市区的id
        $i = array_unique(array_column($data, 'pid')); // id
        foreach ($data as $k => $v) {
            if (in_array($v['pid'], $pids)) {
                //unset($v['pid']);
                if ($type == 0) {
                    $p[] = $v['value'];
                    $d[$v['value']] = $v;
                } else {
                    $p[] = $v['key'];
                    $d[$v['key']] = $v;
                }
            }
        }
        if (in_array($p[0], $i)) {
            $dd = self::resetArea($data, $p, $type);
            foreach ($dd as $k => $v) {
                $d[$v['pid']]['children'][] = $v;
            }
        }
        $back = [];
        foreach ($d as $k => $v) {
            $back[] = $v;
        }
        return $back;
    }

    public function getAreaPath($level = 0, $path = '')
    {
        $pathList = cache('area_path' . $level);
        if (!$pathList) {
            $area = self::getCache();
            $temp = [];
            if ($level) {
                foreach ($area as $k => $v) {
                    if ($v['level'] == $level) {
                        $temp[] = $v;
                    }
                }
                $area = $temp;
            }
            $pathList = array_column($area, 'address', 'path');
            cache('area_path' . $level, $pathList, null, 'area');
        }
        if ($path) {
            $pathList = isset($pathList[$path]) ? $pathList[$path] : '';
        }
        return $pathList;
    }

    public function getName($arr, $type = 'string')
    {
        $temp = [];
        $area = $this->getCache();
        if (!is_array($arr)) {
            $arr = explode(',', $arr);
        }
        foreach ($arr as $k => $v) {
            $temp[$v] = isset($area[$v]) ? $area[$v] : '';
        }
        if ($type == 'string') {
            $temp = implode(' ', array_column($temp, 'name'));
        }
        return $temp;
    }
    public function getCache($flag = false)
    {
        cache("area", null);
        if ($flag) {
            $ans = $this->listTable('area', ['order' => 'id asc', 'limitSize' => 10000]);
            $new = array_column($ans, null, 'id');
            cache("area", $new);
        }
        $ans = cache("area");
        if (!$ans) {
            $ans = $this->listTable('area', ['order' => 'id asc', 'limitSize' => 10000]);
            $ans = array_column($ans, null, 'id');
            cache("area", $ans);
        }
        return $ans;
    }

    public function getCacheWithLevel($flag = false, $level = 1)
    {
        if ($flag) {
            $ans = $this->listTable('area', ['where' => [
                ['level', 'eq', $level],
            ], 'order' => 'id asc', 'limitSize' => 10000]);
            $new = array_column($ans, null, 'id');
            cache("area_" . $level, $new);
        }
        $ans = false;
        if (!$ans) {
            $ans = $this->listTable('area', ['where' => [
                ['level', 'between', [1, $level]],
            ], 'order' => 'id asc', 'limitSize' => 10000]);
            $ans = array_column($ans, null, 'id');
            cache("area_" . $level, $ans, '', 'area');
        }
        return $ans;
    }

    /**根据层级获取地址树
     * @param $areaList
     * @param $pid
     * @param $level
     */
    public function getAreaWithLevel($areaList, $pid, $level, $levelTarget)
    {
        $arr = [];
        foreach ($areaList as $key => $area) {
            if ($area['pid'] = $pid) {
                if ($level != $levelTarget) {
                    $level = $level + 1;
                    $area['chilren'] = $this->getAreaWithLevel($areaList, $area['pid'], $level, $levelTarget);
                }
                $arr[] = $area;
            }
        }
        return $arr;
    }
}
